Handle Auto Suggestion Dropdown
Code of Auto Suggestion
package asc; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class autoSuggestion { public static void main(String[] args) throws InterruptedException { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://www.youtube.com/"); driver.manage().window().maximize(); driver.findElement(By.xpath("//input[@placeholder='Search']")).click(); // Thread.sleep(2000); WebElement from = driver.findElement(By.xpath("//input[@placeholder='Search']")); from.sendKeys("it training classes"); Thread.sleep(2000); from.sendKeys(Keys.ARROW_DOWN); Thread.sleep(2000); from.sendKeys(Keys.ENTER); } }
Output



In Selenium WebDriver, handling auto-suggestion dropdowns involves interacting with elements that appear dynamically as the user types into an input field. Here’s a breakdown of your code and how it handles the auto-suggestion dropdown on YouTube:
1. Setup WebDriver:
WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://www.youtube.com/"); driver.manage().window().maximize();
2. Locate Search Input:
WebElement from = driver.findElement(By.xpath("//input[@placeholder='Search']"));
3. Typing in Search Box:
from.sendKeys("it training classes"); Thread.sleep(2000);
Navigating Auto-Suggestions:
from.sendKeys(Keys.ARROW_DOWN); Thread.sleep(2000); from.sendKeys(Keys.ENTER);
Key Points in Auto-Suggestion Handling
- Waiting for Suggestions: Auto-suggestions can take time to appear due to network latency or page load times. Using Thread.sleep() is a basic way to wait.
- Navigating the Dropdown: You can use Keys.ARROW_DOWN or Keys.ARROW_UP to move through the suggestions. Keys.ENTER or Keys.RETURN can be used to select a suggestion.